//
//  MSPhoneLoginController.m
//  MSJD
//
//  Created by xiangbo on 2018/9/24.
//  Copyright © 2018 xiangbo. All rights reserved.
//

#import "MSPhoneLoginController.h"

#import "MSResetPswController.h"

#import "MSNewTextField.h"

#import "AppDelegate.h"
#import "MSLoginManager.h"

@interface MSPhoneLoginController ()
<UITextFieldDelegate>

@property(nonatomic,strong) UIImageView *logoIcon;

@property (nonatomic, strong) MSNewTextField *phoneTextField;
@property (nonatomic, strong) MSNewTextField *pswTextField;
@property (nonatomic, strong) UIButton *loginButton;
@property (nonatomic, strong) UIButton *wechatLogin; // 微信登录按钮
@property (nonatomic, strong) UIButton *registButton;
@property (nonatomic, strong) UIView *lineView;
@property (nonatomic, strong) UIButton *forgotPswButton;

@property (nonatomic, strong) MSLoginManager *loginManager; // 登录管理器

@end

@implementation MSPhoneLoginController 

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.wechatLogin.hidden = YES;
    [self setupSubviews];
    
    self.loginManager = [MSLoginManager loadLoginManagerWithCurrentVC:self];
    _WEAKSELF
    self.loginManager.LoginSuccessBlock = ^(NSInteger type) {
        [weakSelf loginSuccessWithType:type];
    };
    self.loginManager.LoginFailedBlock = ^(NSInteger type) {
        [weakSelf refreshLoginButtonStatusWithType:type];
    };
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.registButton.enabled = YES;
    self.navigationController.navigationBarHidden = YES;
    // FIXME:
    if (self.loginManager && self.loginManager.type == 1) {
        [self.loginManager removeWechatLoginNotification];
    }
}

- (void)setupSubviews {
    // LOGO
    self.logoIcon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"logo"]];
    [self.baseView addSubview:self.logoIcon];
    
    // 手机号码输入框
    self.phoneTextField = [MSNewTextField loadNewTextFieldWithType:MSTextTypePhone];
    self.phoneTextField.textField.delegate = self;
    [self.baseView addSubview:self.phoneTextField];
    
    // 密码输入框
    self.pswTextField = [MSNewTextField loadNewTextFieldWithType:MSTextTypePwd];
    self.pswTextField.textField.delegate = self;
    [self.baseView addSubview:self.pswTextField];
    
    // 登录按钮
    self.loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.loginButton setTitle:@"登录" forState:UIControlStateNormal];
    [self.loginButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.loginButton.titleLabel.font = [UIFont systemFontOfSize:15];
    self.loginButton.backgroundColor = MSThemeColor;
    [self.loginButton addTarget:self action:@selector(loginButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    self.loginButton.enabled = NO;
    self.loginButton.layer.cornerRadius = 25.0;
    [self.baseView addSubview:self.loginButton];
    
    // 微信登录按钮
    self.wechatLogin = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.wechatLogin setTitle:@"微信登录" forState:UIControlStateNormal];
    [self.wechatLogin setTitleColor:[UIColor colorWithHexString:@"#444444"] forState:UIControlStateNormal];
    self.wechatLogin.titleLabel.font = [UIFont systemFontOfSize:15];
    self.wechatLogin.layer.cornerRadius = 25.0;
    self.wechatLogin.layer.borderWidth = 1.0;
    self.wechatLogin.layer.borderColor = [UIColor colorWithHexString:@"#DDDDDD"].CGColor;
    [self.wechatLogin addTarget:self action:@selector(wechatLoginButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.baseView addSubview:self.wechatLogin];
    
    self.lineView = [[UIView alloc] init];
    self.lineView.backgroundColor = MSThemeColor;
    [self.baseView addSubview:self.lineView];
    
    // 忘记密码按钮
    self.forgotPswButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.forgotPswButton setTitle:@"忘记密码" forState:UIControlStateNormal];
    self.forgotPswButton.titleLabel.font = [UIFont systemFontOfSize:13];
    [self.forgotPswButton setTitleColor:MSThemeColor forState:UIControlStateNormal];
    [self.forgotPswButton addTarget:self action:@selector(forgotPsw) forControlEvents:UIControlEventTouchUpInside];
    [self.baseView addSubview:self.forgotPswButton];
    
    self.registButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.registButton setTitle:@"快速注册" forState:UIControlStateNormal];
    self.registButton.titleLabel.font = [UIFont systemFontOfSize:13];
    [self.registButton setTitleColor:MSThemeColor forState:UIControlStateNormal];
    [self.registButton addTarget:self action:@selector(registerButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.baseView addSubview:self.registButton];
    
    [self addSubviewsMasory];
}

- (void)addSubviewsMasory{
    CGFloat textFieldHeight = 50;
    CGFloat textLeft = 25;

    CGFloat logoWidth = 72;
    CGFloat logoHeight = 72;
    [self.logoIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.baseView);
        make.top.offset(80);
        make.height.mas_equalTo(logoHeight);
        make.width.mas_equalTo(logoWidth);
    }];

    [self.phoneTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.logoIcon.mas_bottom).offset(54);
        make.left.offset(textLeft);
        make.right.offset(-textLeft);
        make.height.mas_equalTo(textFieldHeight);
    }];

    [self.pswTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.phoneTextField.mas_bottom).offset(15);
        make.centerX.equalTo(self.baseView);
        make.width.equalTo(self.phoneTextField);
        make.height.equalTo(self.phoneTextField);
    }];

    [self.loginButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.pswTextField.mas_bottom).offset(40);
        make.left.offset(textLeft);
        make.right.offset(-textLeft);
        make.height.mas_equalTo(textFieldHeight);
    }];
    // 微信登录
    [self.wechatLogin mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.loginButton.mas_bottom).offset(15);
        make.left.offset(textLeft);
        make.right.offset(-textLeft);
        make.height.offset(textFieldHeight);
    }];
    // 中间的line view
    CGFloat lineHeight = 18.0;
    [self.lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.offset(-40);
        make.width.offset(1.0);
        make.height.offset(lineHeight - 2.0);
        make.centerX.equalTo(self.baseView);
    }];
    // 忘记密码
    [self.forgotPswButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.lineView.mas_centerY);
        make.right.equalTo(self.lineView.mas_left).offset(-5);
        make.width.offset(60);
        make.height.mas_equalTo(lineHeight);
    }];
    // 注册
    [self.registButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.lineView.mas_centerY);
        make.left.equalTo(self.lineView.mas_right).offset(5);
        make.width.offset(60);
        make.height.mas_equalTo(lineHeight);
    }];
    // baseView取整个view的尺寸
    [self.baseView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.centerX.centerY.equalTo(self.view);
    }];
}

#pragma mark - UITextField

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if ([MSSafeObject isNull:string] &&
        textField.text.length == 1) {
        // 当前点击的是删除按钮，且当前只有一个字符串
        self.loginButton.enabled = NO;
    } else {
        self.loginButton.enabled = YES;
    }
    return YES;
}

#pragma mark - Reset Method

- (void)keyboardWillShow:(NSNotification *)notification {
    if ([self.pswTextField.textField isFirstResponder]) {
        // 密码输入框弹出
        // 计算键盘高度
        CGRect keyboardFrame = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
        CGFloat height = keyboardFrame.size.height;
        // 得到密码输入框的位置
        CGFloat maxY = CGRectGetMaxY(self.pswTextField.frame) + CGRectGetMinY(self.baseView.frame);
        if (maxY + height > MS_SCREEN_HEIGHT) {
            // 键盘和密码输入框的位置大于界面的高度，则修改baseView的中心点位置
            self.baseView.center = CGPointMake(CGRectGetWidth(self.view.frame) / 2, self.baseView.center.y - (maxY + height - MS_SCREEN_HEIGHT));
        }
    }
}

#pragma mark - Event Response
/** 注册按钮点击 */
- (void)registerButtonClick:(UIButton *)sender {
    sender.enabled = NO;
    [self.view endEditing:YES];
    
    MSResetPswController *registerVC = [MSResetPswController loadResetPswControllerWithType:MSResetPswTypeRegist fromVC:MSResetPwsFromVCTypeLogin];
    [self.navigationController pushViewController:registerVC animated:YES];
}
// 忘记密码按钮点击
- (void)forgotPsw {
    [self.view endEditing:YES];
    // FIXME:
    MSResetPswController *findPswVC = [MSResetPswController loadResetPswControllerWithType:MSResetPswTypeModify fromVC:MSResetPwsFromVCTypeLogin];
    [self.navigationController pushViewController:findPswVC animated:YES];
}
// 登录按钮点击
- (void)loginButtonClick:(UIButton *)sender {
    [self.view endEditing:YES];
    // 判断账号以及密码内容
    if ([MSSafeObject isNull:self.phoneTextField.textField.text]) {
        [MBProgressHUD showDefaultHUDWithText:@"请输入账号" toView:self.view];
        return;
    }
    
    if ([MSSafeObject isNull:self.pswTextField.textField.text]) {
        [MBProgressHUD showDefaultHUDWithText:@"请输入密码" toView:self.view];
        return;
    }
    NSString *phone = [MSSafeObject stringInfo:self.phoneTextField.textField.text];
    NSString *pwd = [MSSafeObject stringInfo:self.pswTextField.textField.text];
    // 请求过程中不可点
    sender.enabled = NO;
    
    [self.loginManager phoneLoginWithPhone:phone pwd:pwd];
}
/** 微信登录按钮点击 */
- (void)wechatLoginButtonClick:(UIButton *)sender {
    // FIXME:
    [self loginSuccessWithType:0];
//    [self.loginManager wechatLogin];
}

#pragma mark - Private Method
/** 登录成功的消息 */
- (void)loginSuccessWithType:(NSInteger)type {
    [self refreshLoginButtonStatusWithType:type];
    if (type == 0) {
        // 手机号码登录成功
        [self dismissViewControllerAnimated:YES completion:nil];
    } else {
        // 微信登录成功
        // 判断是否有绑定的手机号码
        NSString *phone = [UserAccesser loadAccount].phone;
        if ([MSSafeObject isNull:phone]) {
            // 为绑定过手机号进入绑定手机界面
            MSResetPswController *registerVC = [MSResetPswController loadResetPswControllerWithType:MSResetPswTypeBindPhone fromVC:MSResetPwsFromVCTypeLogin];
            [self.navigationController pushViewController:registerVC animated:YES];
            return;
        }
        // 页面跳转
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}
/** 登录失败的消息 */
- (void)refreshLoginButtonStatusWithType:(NSInteger)type {
    if (type == 0) {
        self.loginButton.enabled = YES;
    } else {
        self.wechatLogin.enabled = YES;
    }
}

#pragma mark -  Memory Method

- (void)dealloc {
    NSLog(@"%s", __func__);
}

@end
